import React, { Component } from "react";

import logo from "./logo.svg";
import "./App.css";
import Axios from "axios";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: "hello react",
      todoList: []
    };
  }

  queryTodoList = () => {
    let _this = this;

    Axios.get("http://localhost:8080/query_todo").then(response => {
      _this.setState({
        todoList: response.data
      });
    });
  };

  componentDidMount() {
    this.queryTodoList();
  }

  handleAdd = () => {
    const name = this.todoItem.value;
    // 注意这里的url地址使用的是字符串模版语法，使用``符号包起来。
    Axios.get(`http://localhost:8080/add_todo?name=${name}`).then(response => {
      this.queryTodoList();
    });
  };

  handleDelete = id => {
    Axios.get(`http://localhost:8080/delete_todo?id=${id}`).then(response => {
      this.queryTodoList();
    });
  };

  render() {
    const todoList = this.state.todoList;

    return (
      <div className="App">
        <input type="text" ref={instance => (this.todoItem = instance)} />
        <button onClick={this.handleAdd}>add</button>

        <ul>
          {todoList.map(item => {
            return (
              <li key={item.id}>
                {item.name}
                <button onClick={() => this.handleDelete(item.id)}>x</button>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}

export default App;
